#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
真实衰减值计算示例
演示修改后的_record_data方法如何计算和存储真实衰减值
"""

def demo_attenuation_calculation():
    """演示真实衰减值计算"""
    print("📊 真实衰减值计算示例")
    print("=" * 50)
    
    # 模拟测试数据
    test_scenarios = [
        {
            "frequency": 1000.0,
            "sg_level": 10.0,      # 信号源输出功率 (dBm)
            "attenuation": 20.0,   # 设定衰减值 (dB) 
            "measured_value": -12.5, # 频谱仪测量值 (dBm)
            "reference_loss": -1.1   # 参考线线损 (dB)
        },
        {
            "frequency": 2400.0,
            "sg_level": 15.0,
            "attenuation": 30.0,
            "measured_value": -18.2,
            "reference_loss": -1.8
        },
        {
            "frequency": 5800.0,
            "sg_level": 5.0,
            "attenuation": 50.0,
            "measured_value": -47.5,
            "reference_loss": -2.3
        }
    ]
    
    print("🔍 计算逻辑说明:")
    print("1. 补偿后测量值 = 原始测量值 - 参考线线损")
    print("2. 真实衰减值 = 信号源输出功率 - 补偿后测量值")
    print("3. 数据存储: calibration_data[设定衰减][频率] = 真实衰减值")
    print()
    
    calibration_data = {}
    
    for i, scenario in enumerate(test_scenarios, 1):
        freq = scenario["frequency"]
        sg_level = scenario["sg_level"]
        attenuation = scenario["attenuation"]
        measured_value = scenario["measured_value"]
        reference_loss = scenario["reference_loss"]
        
        print(f"📋 测试场景 {i}:")
        print(f"   频率: {freq} MHz")
        print(f"   信号源输出: {sg_level} dBm")
        print(f"   设定衰减: {attenuation} dB")
        print(f"   原始测量值: {measured_value} dBm")
        print(f"   参考线线损: {reference_loss} dB")
        
        # 计算补偿后测量值
        compensated_value = measured_value - reference_loss
        compensated_value = round(compensated_value, 2)
        
        # 计算真实衰减值
        actual_attenuation = sg_level - compensated_value
        actual_attenuation = round(actual_attenuation, 2)
        
        print(f"   补偿后测量值: {compensated_value} dBm")
        print(f"   ✨ 真实衰减值: {actual_attenuation} dB")
        
        # 存储数据
        if attenuation not in calibration_data:
            calibration_data[attenuation] = {}
        calibration_data[attenuation][freq] = actual_attenuation
        
        # 分析衰减误差
        attenuation_error = actual_attenuation - attenuation
        print(f"   📈 衰减误差: {attenuation_error:+.2f} dB")
        print()
    
    print("💾 最终数据结构:")
    print("calibration_data = {")
    for att_setting, freq_data in sorted(calibration_data.items()):
        print(f"    {att_setting}: {{")
        for freq, actual_att in sorted(freq_data.items()):
            print(f"        {freq}: {actual_att},")
        print("    },")
    print("}")
    print()
    
    print("🎯 数据结构优势:")
    print("✅ 直接存储真实衰减值，便于分析")
    print("✅ 简化数据访问，无需解析嵌套字典")
    print("✅ 便于计算衰减器误差和线性度")
    print("✅ 数据格式清晰，易于后续处理")
    
    return calibration_data

def demo_data_analysis(calibration_data):
    """演示数据分析"""
    print("\n📊 数据分析示例")
    print("=" * 50)
    
    # 分析衰减器性能
    for att_setting in sorted(calibration_data.keys()):
        freq_data = calibration_data[att_setting]
        actual_attenuations = list(freq_data.values())
        
        # 计算统计信息
        avg_actual = sum(actual_attenuations) / len(actual_attenuations)
        max_actual = max(actual_attenuations)
        min_actual = min(actual_attenuations)
        
        # 计算误差
        avg_error = avg_actual - att_setting
        max_error = max_actual - att_setting
        min_error = min_actual - att_setting
        
        print(f"🔧 设定衰减: {att_setting} dB")
        print(f"   平均实际衰减: {avg_actual:.2f} dB")
        print(f"   实际衰减范围: {min_actual:.2f} ~ {max_actual:.2f} dB")
        print(f"   平均误差: {avg_error:+.2f} dB")
        print(f"   误差范围: {min_error:+.2f} ~ {max_error:+.2f} dB")
        print()

def demo_json_output(calibration_data):
    """演示JSON输出格式"""
    print("📄 JSON输出格式示例")
    print("=" * 50)
    
    import json
    
    # 生成时间戳文件名
    import time
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"calibration_data_{timestamp}.json"
    
    # 模拟保存
    json_str = json.dumps(calibration_data, indent=4, ensure_ascii=False)
    print(f"📁 文件名: {filename}")
    print("📝 文件内容:")
    print(json_str)
    
    print(f"\n💡 数据访问示例:")
    print("# 获取30dB衰减在2400MHz的真实衰减值")
    if 30.0 in calibration_data and 2400.0 in calibration_data[30.0]:
        actual_att = calibration_data[30.0][2400.0]
        print(f"actual_attenuation = calibration_data[30.0][2400.0]  # = {actual_att} dB")

if __name__ == "__main__":
    print("🚀 真实衰减值计算和存储演示")
    print("=" * 60)
    
    # 演示计算过程
    calibration_data = demo_attenuation_calculation()
    
    # 演示数据分析
    demo_data_analysis(calibration_data)
    
    # 演示JSON输出
    demo_json_output(calibration_data)
    
    print("=" * 60)
    print("✅ 演示完成！新的数据结构更简洁、直观，便于后续分析。")